package com.mote;

import java.security.MessageDigest;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;

import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;

import android.content.SharedPreferences;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import android.widget.ListView;

public class Login extends Activity {

	public ListView m_listView;

	HttpGet httpReq;
	HttpResponse httpRes;
	HttpClient httpClient;

	String httpUrl = "http://fuzhijie.me/mote/user.php?act=login";

	private Button btn_login;
	private Button btn_register;

	private EditText et_account;
	private EditText et_password;
	
	private static int SAMEUSER = -2;
	
	private String user;

	private SharedPreferences mSettings;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.login);

		mSettings = getSharedPreferences("mote", 0);

		findViews();

		setListensers();
	}

	private void findViews() {
		btn_login = (Button) findViewById(R.id.login);

		et_account = (EditText) findViewById(R.id.account);
		et_account.setText("qingfei@taobao.com");

		et_password = (EditText) findViewById(R.id.password);

		user = getIntent().getStringExtra("user");

		et_account.setText(user);
	}

	private void setListensers() {
		btn_login.setOnClickListener(login);
	}

	private OnClickListener login = new OnClickListener() {
		public void onClick(View v) {
			String account = et_account.getText().toString();
			String password = et_password.getText().toString();

			MessageDigest md;

			try {
				md = MessageDigest.getInstance("MD5");

				// 对密码进行md5
				byte[] mdBytes = md.digest(password.getBytes());

				StringBuffer sb = new StringBuffer();

				for (int i = 0; i < mdBytes.length; i++) {
					int val = ((int) mdBytes[i]) & 0xff;
					if (val < 16)
						sb.append("0");
					sb.append(Integer.toHexString(val));
				}

				HttpPost httpPost = new HttpPost(httpUrl);

				List<NameValuePair> params = new ArrayList<NameValuePair>();

				// 通过POST方式把用户名和密码传到服务器
				params.add(new BasicNameValuePair("loginUn", account));
				params.add(new BasicNameValuePair("loginPw", sb.toString()));

				// 设置字符集？？
				HttpEntity httpEntity = new UrlEncodedFormEntity(params);

				httpPost.setEntity(httpEntity);

				HttpClient httpClient = new DefaultHttpClient();

				// 发送请求
				HttpResponse httpResponse = httpClient.execute(httpPost);

				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					String strResult = EntityUtils.toString(httpResponse
							.getEntity());

					// 如果登录正确，服务器会发送token过来；登录失败时，服务器什么也不会返回
					if (!"".equals(strResult)) {

						// 将sync置空，这样MoteService不会再同步了
						mSettings.edit().remove("sync").commit();

						int start = strResult.indexOf("token\">") + 7;

						strResult = strResult.substring(start,
								strResult.length() - 7);

						mSettings.edit().putString("user", account)
								.putString("token", strResult)
								.remove("last_mote_id").commit();

						if (user.equals(account)) {
							setResult(SAMEUSER);
						}
						else {
							setResult(RESULT_OK);	
						}

						finish();
					} else {
						Toast.makeText(Login.this, "登录失败", Toast.LENGTH_LONG)
								.show();
					}
				}
			} catch (Exception e) {

				e.printStackTrace();
			}
		}
	};
}